import sys
import PyQt5
from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QSystemTrayIcon, QAction, QWidget
import qtawesome as qta

from global_data.glabal_data import GlobalData
from utils.dialog_utils import DialogUtils


class SystemTrayApp(object):
    def __init__(self, main_app, main_win):
        super().__init__()
        self.main_app = main_app
        self.main_win = main_win
        self.icon = qta.icon(GlobalData.TRAY_ICON)
        self.initUI()

    def initUI(self):
        # 设置窗口不显示
        # self.main_app.hide()

        # 创建系统托盘图标
        self.tray = QSystemTrayIcon(self.main_win)
        self.tray.setIcon(self.icon)  # 替换为你的图标路径
        self.tray.setToolTip('系统托盘程序')
        # 创建弹出菜单
        self.menu = QMenu()
        self.show_action = QAction('显示窗口', self.tray)
        self.quit_action = QAction('退出', self.tray)
        # 将动作添加到弹出菜单
        self.menu.addAction(self.show_action)
        self.menu.addAction(self.quit_action)

        # 设置托盘图标的弹出菜单
        self.tray.setContextMenu(self.menu)
        # 信号和槽函数连接
        self.tray.activated.connect(self.icon_activated)
        self.show_action.triggered.connect(self.show_window)
        self.quit_action.triggered.connect(self.quit_app)
        # 添加托盘图标到系统托盘区
        self.tray.setVisible(True)
        self.tray.show()

    def icon_activated(self, reason):
        """
        托盘点击事件
        """
        # 鼠标点击icon传递的信号会带有一个整形的值，1是表示单击右键，2是双击，3是单击左键，4是用鼠标中键点击
        if reason in (QSystemTrayIcon.DoubleClick, QSystemTrayIcon.MiddleClick):
            if self.main_win.isMinimized() or not self.main_win.isVisible():
                self.show_window()
            else:
                self.hide_window()

    def show_window(self):
        # self.tray.showMessage("提示", "你点了消息", self.icon)
        # 若是最小化，则先正常显示窗口，再变为活动窗口（暂时显示在最前面）
        self.main_win.showNormal()
        self.main_win.activateWindow()
        self.main_win.setWindowFlags(QtCore.Qt.Window)
        self.main_win.show()

    def hide_window(self):
        # 若不是最小化，则最小化
        self.main_win.showMinimized()
        self.main_win.setWindowFlags(QtCore.Qt.SplashScreen)
        self.main_win.hide()

    def quit_app(self):
        res = DialogUtils.confirm("确认退出程序吗？", "提示")
        if DialogUtils.checkRes(res):
            # for widget in QApplication.instance().allWidgets():
            for widget in QApplication.topLevelWidgets():
                if isinstance(widget, QWidget) and widget != self.main_win:
                    if widget.isHidden():  # 检查窗口是否已经被隐藏（即关闭）
                        continue;
                    widget.close()
                    self.main_app.topLevelWidgets().remove(widget)  # 从应用程序的顶级窗口列表中移除窗口
            self.main_win.close()
            self.tray.setVisible(False)
            self.main_app.quit()
            PyQt5.QtWidgets.qApp.quit
            sys.exit(0)
            QApplication.exit(0)  # 退出程序


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = SystemTrayApp()
    sys.exit(app.exec_())
